package com.starrocks.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starrocks.entity.SyncLogEntity;
import com.starrocks.mapper.SyncLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 同步日志服务
 */
@Slf4j
@Service
public class SyncLogService {

    @Autowired
    private SyncLogMapper syncLogMapper;

    /**
     * 创建日志记录（同步开始时）
     */
    public SyncLogEntity createLog(Long configId, String sourceTableName, String targetTableName, String syncType) {
        SyncLogEntity logEntity = new SyncLogEntity();
        logEntity.setConfigId(configId);
        logEntity.setSourceTableName(sourceTableName);
        logEntity.setTargetTableName(targetTableName);
        logEntity.setSyncType(syncType);
        logEntity.setSyncStatus("RUNNING");
        logEntity.setStartTime(LocalDateTime.now());
        logEntity.setTotalCount(0);
        logEntity.setSuccessCount(0);
        logEntity.setFailCount(0);
        
        syncLogMapper.insert(logEntity);
        return logEntity;
    }

    /**
     * 更新日志记录（同步完成时）
     */
    public void updateLog(Long logId, String syncStatus, Integer totalCount, Integer successCount, 
                         Integer failCount, LocalDateTime lastSyncTime, String errorMessage) {
        updateLog(logId, syncStatus, totalCount, successCount, failCount, lastSyncTime, errorMessage, null);
    }
    
    /**
     * 更新日志记录（同步完成时，支持保存源数据）
     */
    public void updateLog(Long logId, String syncStatus, Integer totalCount, Integer successCount, 
                         Integer failCount, LocalDateTime lastSyncTime, String errorMessage, String sourceData) {
        SyncLogEntity logEntity = syncLogMapper.selectById(logId);
        if (logEntity != null) {
            logEntity.setSyncStatus(syncStatus);
            logEntity.setEndTime(LocalDateTime.now());
            logEntity.setTotalCount(totalCount);
            logEntity.setSuccessCount(successCount);
            logEntity.setFailCount(failCount);
            
            // 🔥 防御性检查：确保 lastSyncTime 在数据库允许的范围内
            // MySQL datetime 范围：'1000-01-01 00:00:00' 到 '9999-12-31 23:59:59'
            if (lastSyncTime != null && lastSyncTime.getYear() >= 1000 && lastSyncTime.getYear() <= 9999) {
                logEntity.setLastSyncTime(lastSyncTime);
            } else {
                // 如果时间无效，使用当前时间或 null
                logEntity.setLastSyncTime(null);
            }
            
            logEntity.setErrorMessage(errorMessage);
            
            // 仅在失败时保存源数据（避免数据库存储过大）
            if ("FAILED".equals(syncStatus) && sourceData != null) {
                logEntity.setSourceData(sourceData);
            }
            
            // 计算执行时长
            if (logEntity.getStartTime() != null && logEntity.getEndTime() != null) {
                long duration = java.time.Duration.between(logEntity.getStartTime(), logEntity.getEndTime()).toMillis();
                logEntity.setDuration(duration);
            }
            
            syncLogMapper.updateById(logEntity);
        }
    }

    /**
     * 分页查询日志
     */
    public IPage<SyncLogEntity> pageList(int pageNum, int pageSize, Long configId, String sourceTableName, 
                                        String targetTableName, String syncType, String syncStatus) {
        Page<SyncLogEntity> page = new Page<>(pageNum, pageSize);
        
        LambdaQueryWrapper<SyncLogEntity> wrapper = new LambdaQueryWrapper<>();
        if (configId != null) {
            wrapper.eq(SyncLogEntity::getConfigId, configId);
        }
        if (sourceTableName != null && !sourceTableName.isEmpty()) {
            wrapper.eq(SyncLogEntity::getSourceTableName, sourceTableName);
        }
        if (targetTableName != null && !targetTableName.isEmpty()) {
            wrapper.eq(SyncLogEntity::getTargetTableName, targetTableName);
        }
        if (syncType != null && !syncType.isEmpty()) {
            wrapper.eq(SyncLogEntity::getSyncType, syncType);
        }
        if (syncStatus != null && !syncStatus.isEmpty()) {
            wrapper.eq(SyncLogEntity::getSyncStatus, syncStatus);
        }
        
        wrapper.orderByDesc(SyncLogEntity::getStartTime);
        
        return syncLogMapper.selectPage(page, wrapper);
    }

    /**
     * 查询最近N条日志
     */
    public List<SyncLogEntity> getRecentLogs(int limit) {
        LambdaQueryWrapper<SyncLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SyncLogEntity::getStartTime);
        wrapper.last("LIMIT " + limit);
        
        return syncLogMapper.selectList(wrapper);
    }

    /**
     * 查询指定配置的最新日志
     */
    public SyncLogEntity getLatestLog(String sourceTableName, String targetTableName) {
        LambdaQueryWrapper<SyncLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SyncLogEntity::getSourceTableName, sourceTableName);
        wrapper.eq(SyncLogEntity::getTargetTableName, targetTableName);
        wrapper.orderByDesc(SyncLogEntity::getStartTime);
        wrapper.last("LIMIT 1");
        
        return syncLogMapper.selectOne(wrapper);
    }

    /**
     * 删除指定配置的日志
     */
    public void deleteByConfigId(Long configId) {
        LambdaQueryWrapper<SyncLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SyncLogEntity::getConfigId, configId);
        syncLogMapper.delete(wrapper);
    }

    /**
     * 清理指定天数之前的日志
     */
    public int cleanOldLogs(int days) {
        LocalDateTime beforeDate = LocalDateTime.now().minusDays(days);
        LambdaQueryWrapper<SyncLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(SyncLogEntity::getStartTime, beforeDate);
        
        return syncLogMapper.delete(wrapper);
    }
}
